<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator函数的异步应用</title>
</head>
<body>
    <h1>Generator函数的异步应用</h1>

    <script>
        // 使用Generator函数处理异步操作
        function* main() {
            const result = yield request('https://api.example.com/data');
            const data = JSON.parse(result);
            console.log(data);
        }

        // 模拟请求函数
        function request(url) {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve('{"name": "张三", "age": 20}');
                }, 1000);
            });
        }

        // 执行Generator函数
        function run(generator) {
            const it = generator();

            function next(data) {
                const result = it.next(data);
                if (result.done) return result.value;
                result.value.then(data => next(data));
            }

            next();
        }

        run(main);

        // 多个异步操作
        function* loadData() {
            try {
                const users = yield fetchUsers();
                console.log('用户数据:', users);
                
                const posts = yield fetchPosts(users[0].id);
                console.log('文章数据:', posts);
                
                const comments = yield fetchComments(posts[0].id);
                console.log('评论数据:', comments);
            } catch (error) {
                console.log('加载出错:', error);
            }
        }

        // 模拟数据获取函数
        function fetchUsers() {
            return Promise.resolve([
                { id: 1, name: '张三' }
            ]);
        }

        function fetchPosts(userId) {
            return Promise.resolve([
                { id: 1, title: '文章1', userId }
            ]);
        }

        function fetchComments(postId) {
            return Promise.resolve([
                { id: 1, content: '评论1', postId }
            ]);
        }

        // 执行异步操作
        run(loadData);
    </script>
</body>
</html> 